package com.sxkiler.demo.rpc.client;

import com.sxkiler.demo.rpc.common.MessageDecoder;
import com.sxkiler.demo.rpc.common.MessageEncoder;
import com.sxkiler.demo.rpc.pojo.Book;
import com.sxkiler.demo.rpc.service.BookService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        // NacosTemplate nacosTemplate = new NacosTemplate();//集成nacos用，这里可以去掉
        NettyClientHandler nettyClientHandler = new NettyClientHandler();
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MessageDecoder());//自定义解码器
                            pipeline.addLast(new MessageEncoder());//自定义编码器
                            pipeline.addLast(nettyClientHandler);
                        }
                    });

            //集成nacos用，这里可以去掉。从nacos中负载均衡获取一个健康的服务实例
            /*Instance nettyServices = nacosTemplate.getOneHealthyInstance("nettyServices");
            ChannelFuture future = bootstrap.connect(nettyServices.getIp(), nettyServices.getPort()).sync();*/
            ChannelFuture future = bootstrap.connect("localhost", 8881).sync();

            if (future.isSuccess()){
                System.out.println("连接到服务端，开始调用服务");
                //客户端核心处理都在这个InvokeService里
                InvokeService InvokeService = new InvokeService(BookService.class,nettyClientHandler);
                Book book = InvokeService.getBook(1);//调用远程服务，对于客户端来接屏蔽了调用过程，只返回数据
                System.out.println("---getBook返回结果："+book.toString());
                Integer integer = InvokeService.insertBook(book);
                System.out.println("---insertBook返回结果："+integer.toString());
                Book book1 = InvokeService.updateBook(book);
                System.out.println("---updateBook返回结果："+book1.toString());
                Integer integer1 = InvokeService.delBook(integer);
                System.out.println("---delBook返回结果："+integer1.toString());
            }
            ChannelFuture sync = future.channel().closeFuture().sync();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(eventLoopGroup != null) {
                eventLoopGroup.shutdownGracefully();
            }
        }
    }
}

